#!/bin/bash
#*/1 * * * * /bin/bash /app/shell/upload_obs.sh  minute
#05 00 */1 * * /bin/bash /app/shell/upload_obs.sh  daily
#环境变量,根据每个项目做对应修改
object=xxx
project=xxx
project_url=/app/project/xxx
project_env=wethink
new_num=5
datetime=`date +%d | sed 's/0*\([1-9]\)/\1/g'`

if [[ $project_env == wethink ]];then
    #wethink项目基本是固定resource目录
    static_pwd="resource"
else
    #需要上传的目录,每个项目可能有点小差别
    static_pwd="resource content certificate attachment user item editor poster position poster mobileapp"
fi


#每天整体检查
check_daily(){
    for  cdn_url in  $static_pwd
    do   
        if [[ $project_env == wethink  ]];then
            /usr/local/bin/obsutil cp   $project_url/$cdn_url/  obs://$object/$project/mobile/  -r -f -u    >/dev/null
        else
            /usr/local/bin/obsutil cp   $project_url/$cdn_url/  obs://$object/$project/  -r -f -u     >/dev/null
        fi
    done
}


add_minute(){
    sleep 3
    cd  $project_url
    #如果发现有obsutil进程存在就退出脚本
    if [[ `ps -ef |  grep -v grep | grep obsutil | wc -l`  == 0 ]];then
        for  cdn_url in $static_pwd  
        do           
            if [[ $project_env == wethink  ]];then
                cd $cdn_url
                #获取最新时间目录
                for add_url in `ls -lt  | head -n $new_num  | awk -v datetime=$datetime '{ if ($7==datetime) print $NF}'`
                do
                    #获取最新时间文件
                    for add_file in `ls -lt  $add_url/  | head -n $new_num  | awk -v datetime=$datetime '{ if ($7==datetime) print $NF}'` 
                    do
                        /usr/local/bin/obsutil cp   $project_url/$cdn_url/$add_url/$add_file  obs://$object/$project/mobile/$cdn_url/$add_url/  -r -f -u >/dev/null
                    done
                done    
            else
                #获取最新时间戳的目录
                for add_url in  `ls -lt  $cdn_url/  | head -n $new_num  | awk -v datetime=$datetime '{ if ($7==datetime) print $NF}'` 
                do
                    /usr/local/bin/obsutil cp   $project_url/$cdn_url/$add_url/  obs://$object/$project/$cdn_url/  -r -f -u  >/dev/null
                done
            fi
        done
    else
        exit
    fi   
}


#通过定时任务去跑对应的函数
case $1 in
    minute)     #每分钟运行一次,增量更新
        add_minute
    ;;
    daily)       #每天运行一次整体检查
        check_daily
    ;;
esac